/**
 * Copyright (C) 2014 Luvina Software Company
 * ListUserController.java, Dec 15, 2014, Nguyen Huu Luan LA11_AM
 *
 */
package net.luvina.manageuser.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.luvina.manageuser.entities.MstGroup;
import net.luvina.manageuser.entities.UserInfor;
import net.luvina.manageuser.logics.impl.MstGroupLogicImpl;
import net.luvina.manageuser.logics.impl.TblUserLogicImpl;
import net.luvina.manageuser.utils.Common;
import net.luvina.manageuser.utils.Constant;
import net.luvina.manageuser.utils.MessageProperties;
import net.luvina.manageuser.utils.ProjectProperties;

/**
 * Controller cho các chức năng chính của ứng dụng.
 * 
 * @author luan
 * 
 */
public class ListUserController extends javax.servlet.http.HttpServlet
		implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public ListUserController() {
		super();
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 * HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 * HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {

			TblUserLogicImpl userLogic = new TblUserLogicImpl();
			MstGroupLogicImpl groupLogic = new MstGroupLogicImpl();

			List<MstGroup> listGroup = new ArrayList<MstGroup>();
			List<UserInfor> listUser = new ArrayList<UserInfor>();

			HttpSession session = request.getSession();

			String message = "";
			String target = "";

			String fullName = "";
			int groupId = 0;

			int range;
			int limit;
			int totalRecord;
			int totalPage;
			int totalSection;
			int currentPage = 1;
			int currentSection;
			int maxPage;
			int minPage;
			int offset;

			String sortType = "full_name";
			String sortValue = "ASC";
			String sortByFullName = "ASC";
			String sortByCodeLevel = "DESC";
			String sortByEndDate = "DESC";

			// Kiểm tra xem đã có user nào login chưa, nếu chưa thì chuyển đến
			// màn hình ADM001.
			if (!"".equals(Common.checkLogin(session))) {
				target = Constant.ADM001;
			} else {
				target = Constant.ADM002;
				/*
				 * 
				 * 
				 * 
				 * 
				 * Lấy điều kiện tìm kiếm
				 */
				String fullNameReq = request.getParameter("fullName");
				String groupIdReq = request.getParameter("groupId");
				if (fullNameReq != null || groupIdReq != null) {
					if (fullNameReq != null) {
						fullName = fullNameReq;
					}
					if (groupIdReq != null) {
						groupId = Integer.parseInt(groupIdReq);
					}
				} else {
					Object fullNameSession = session.getAttribute("fullName");
					Object groupIdSession = session.getAttribute("groupId");
					if (fullNameSession != null) {
						fullName = (String) fullNameSession;
					}
					if (groupIdSession != null) {
						groupId = (Integer) groupIdSession;
					}
				}

				// Lưu điều kiện tìm kiếm lên session.
				session.setAttribute("fullName", fullName);
				session.setAttribute("groupId", groupId);

				// Và đồng thời gửi sang ADM002.
				request.setAttribute("fullName", Common.escapeHTML(fullName));
				request.setAttribute("groupId", groupId);

				/*
				 * 
				 * 
				 * 
				 * 
				 * 
				 * 
				 * Lấy dữ liệu hiển thị trang.
				 */
				String pageReq = request.getParameter("page");
				Object pageSession = session.getAttribute("currentPage");
				if (pageReq != null) {
					currentPage = Integer.parseInt(pageReq);
					if (currentPage <= 0) {
						currentPage = 1;
					}
				} else if (pageSession != null) {
					currentPage = (Integer) pageSession;
				}

				// Calculate the paging information.
				totalRecord = userLogic.getTotalRecords(groupId, Common
						.escapeInjection(fullName));
				limit = Integer.parseInt(ProjectProperties.getMessage("limit"));
				range = Integer.parseInt(ProjectProperties.getMessage("range"));
				totalPage = Common.getTotalPage(totalRecord, limit);
				totalSection = (int) Math.ceil((double) totalPage / range);

				offset = Common.getOffset(currentPage, limit);
				currentSection = (int) Math.ceil((double) currentPage / range);

				List<Integer> listPage = Common.getListPaging(limit, range,
						totalPage, currentPage);
				if (listPage.size() == 0) {
					minPage = 1;
					maxPage = 1;
				} else {
					minPage = listPage.get(0);
					maxPage = listPage.get(listPage.size() - 1);
				}

				// Lưu dữ liệu paging lên session.
				session.setAttribute("currentPage", currentPage);

				// Đông thời chuyển dữ liệu hiển thị trang sang ADM002
				request.setAttribute("totalSection", totalSection);
				request.setAttribute("currentSection", currentSection);
				request.setAttribute("minPage", minPage);
				request.setAttribute("maxPage", maxPage);
				request.setAttribute("currentPage", currentPage);
				request.setAttribute("range", range);

				/*
				 * 
				 * 
				 * 
				 * 
				 * 
				 * Lấy thứ tự sắp xếp ưu tiên cho các trường.
				 */
				String sortTypeReq = request.getParameter("sortType");
				Object sortTypeSession = session.getAttribute("sortType");
				if (sortTypeReq != null) {
					sortType = sortTypeReq;
					sortValue = request.getParameter("sortValue");
					if ("full_name".equals(sortType)) {
						sortByFullName = sortValue;
						sortByCodeLevel = "DESC";
						sortByEndDate = "DESC";
					} else if ("code_level".equals(sortType)) {
						sortByCodeLevel = sortValue;
						sortByFullName = "ASC";
						sortByEndDate = "DESC";
					} else if ("end_date".equals(sortType)) {
						sortByEndDate = sortValue;
						sortByFullName = "ASC";
						sortByCodeLevel = "DESC";
					}
				} else if (sortTypeSession != null) {
					sortType = (String) sortTypeSession;
					sortValue = (String) session.getAttribute("sortValue");
					if ("full_name".equals(sortType)) {
						sortByFullName = (String) sortValue;
						sortByCodeLevel = "DESC";
						sortByEndDate = "DESC";
					} else if ("code_level".equals(sortType)) {
						sortByCodeLevel = (String) sortValue;
						sortByFullName = "ASC";
						sortByEndDate = "DESC";
					} else if ("end_date".equals(sortType)) {
						sortByEndDate = (String) sortValue;
						sortByFullName = "ASC";
						sortByCodeLevel = "DESC";
					}
				}
				// Lưu điều kiện sắp xếp lên session.
				session.setAttribute("sortType", sortType);
				session.setAttribute("sortValue", sortValue);

				// và gửi điều kiện sắp xếp sang ADM002.
				request.setAttribute("sortByFullName", sortByFullName);
				request.setAttribute("sortByCodeLevel", sortByCodeLevel);
				request.setAttribute("sortByEndDate", sortByEndDate);

				/*
				 * 
				 * 
				 * 
				 * 
				 * Lấy về danh sách user và danh sách nhóm theo điều kiện tìm
				 * kiếm.
				 */
				listUser = userLogic.getListUsers(offset, limit, groupId,
						Common.escapeInjection(fullName), sortType,
						sortByFullName, sortByCodeLevel, sortByEndDate);
				listGroup = groupLogic.getAllMstGroups();

				if (listUser.size() == 0) {
					message = MessageProperties.getMessage("user_not_found");
				}

				// Gửi tất cả sang màn hình ADM002.
				request.setAttribute("listGroup", listGroup);
				request.setAttribute("listUser", listUser);
				request.setAttribute("message", message);

			}
			// Forward
			RequestDispatcher req = request.getRequestDispatcher(target);
			req.forward(request, response);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
